//
//  FilesViewController.m
//  FuelLog
//
//  Created by Pure Mass Communications on 4/5/09.
//  Copyright 2009 . All rights reserved.
//
//  Placed under GPL v2 with the kind permission of Pure Mass Communications
//
//  Modified to make compile under SDK 3.1 by Olaf Greck in May 2010
//
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import "FuelLogAppDelegate.h"
#import "FuelLogViewController.h"
#import "FilesViewController.h"
#import "CarsViewController.h"
#import "Gas.h"
#import "GdataDocs.h"
#import "GDataSpreadsheet.h"

#import "DebugOutput.h"

@interface FilesViewController (PrivateMethods)
- (void)importCarTicket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataEntryDocBase *)object;
- (void)importCarTicket:(GDataServiceTicket *)ticket failedWithError:(NSError *)error;

- (void)importSheet:(GDataEntryDocBase *)sheet;
- (void)importSheetTicket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataEntryDocBase *)object;
- (void)importSheetTicket:(GDataServiceTicket *)ticket failedWithError:(NSError *)error;

- (void)alertBegin;
- (void)alertSuccess;
- (void)alertFail:(NSString *)error;
@end

@implementation FilesViewController
  
//@synthesize doneButton;
@synthesize ready, cancelled, files, service, spreadsheetService;
 

// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
		ready = NO;
		cancelled = NO;
    }
    return self;
}

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */

/* 
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 debug(@"in viewDidLoad");
 [super viewDidLoad]; 
 self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
 initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
 target:self action:@selector(cancel_Clicked:)] autorelease];
 }
 
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)viewWillAppear:(BOOL)animated {
	debug(@"in viewWillAppear");
	if (!ready && !cancelled) {
		[self performSelector:@selector(showModalViewController) withObject:nil afterDelay:0.6];
		
		/*	
		 LoginViewController *loginController = [FuelLogViewController loginViewController];
		 [loginController setMode:FUELLOG_IMPORT];
		 [loginController setCar:nil];
		 [self presentModalViewController:loginController animated:NO];
		 debug(@"presentModalViewController loginController");
		 */
	}
	cancelled = NO;  
}

- (void)viewDidAppear:(BOOL)animated {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	debug(@"in viewDidAppear");
	debug(@"cancelled is: %d",cancelled);
	[super viewDidAppear:animated];
	if (cancelled) {
		debug(@"cancelled is %d and now dismissing loginController", cancelled);
		[self performSelector:@selector(dismissModalViewController) withObject:nil afterDelay:0.0];
		//		 [self dismissModalViewControllerAnimated:NO];
	}
	cancelled = NO; // */
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	debug(@"in dealloc");
	
	if (files != nil) {
		[files release];
		files = nil;
	}
	if (service != nil) {
		[service release];
		service = nil;
	}
	if (spreadsheetService != nil) {
		[spreadsheetService release];
		spreadsheetService = nil;
	}
    [super dealloc];
}

#pragma mark -

-(void)showModalViewController {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	if (!ready) {
		LoginViewController *loginController = [FuelLogViewController loginViewController];
		//LoginViewController *loginController = [[LoginViewController alloc] initWithNibName:@"Login" bundle:nil];
		
		[loginController setMode:FUELLOG_IMPORT];
		[loginController setCar:nil];
		[self presentModalViewController:loginController animated:NO];
		debug(@"presentModalViewController loginController");
	}
	cancelled = NO;	
}
 

-(void)dismissModalViewController {
	debug(@"dismissModalViewController loginController");
	[self dismissModalViewControllerAnimated:NO];
	ready = NO;
	cancelled = YES;
	debug(@"dismissModalViewController FileViewController");
	[self dismissModalViewControllerAnimated:NO];
	CarsViewController *cvc = (CarsViewController *)self.parentViewController;
	[cvc clickSelectedCar];
}


- (IBAction)done:(id)sender {
	ready = NO;
	cancelled = NO;
	[self dismissModalViewControllerAnimated:YES];
	CarsViewController *cvc = (CarsViewController *)self.parentViewController;
	[cvc clickSelectedCar];
}

- (void)resetData {
	[tableView reloadData];
}

- (void)importCar:(GDataEntryDocBase *)gfile {
	
	debug(@"in importCar");
	
	cancelled = NO;
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	filename = [[[gfile title] stringValue] copy];
	NSString *carname = [filename copy];
	int i = 1;
	while ([appDelegate hasCar:carname]) {
		carname = [NSString stringWithFormat:@"%@_%d", filename, i];
		i++;
	}
	if (newCar != nil) {
		[newCar release];
	}
	newCar = [[Car alloc] init];
	[newCar setLabel:carname];
	
	GDataEntrySpreadsheet *data = (GDataEntrySpreadsheet *) gfile;
    NSURL *feedURL = [[data worksheetsLink] URL];
    if (feedURL) {		
		[spreadsheetService fetchSpreadsheetFeedWithURL:feedURL
											   delegate:self
									  didFinishSelector:@selector(importCarTicket:finishedWithFeed:)
										didFailSelector:@selector(importCarTicket:failedWithError:)];
		[self alertBegin];
    } else {
		[self alertFail:(NSLocalizedString(@"Files_importCar incomplete data",@"Received incomplete data from Google."))];
	}
}

- (void)importCarTicket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataEntryDocBase *)object {
	debug(@"in importCarTicket");
	if (cancelled) {
		return;
	}
	GDataFeedDocList *list = (GDataFeedDocList *) object;
	NSArray *entries = [list entries];
	if ([entries count] > 0) {
		GDataEntryDocBase *sheet = (GDataEntryDocBase *)[entries objectAtIndex:0];
		[self importSheet:sheet];
	} else {
		[self alertFail:(NSLocalizedString(@"Files_importCarTicket_finishedWithFeed no worksheets.",@"File does not have any worksheets.")) ];
	}
} 

- (void)importCarTicket:(GDataServiceTicket *)ticket failedWithError:(NSError *)error {
	[self alertFail:(NSLocalizedString(@"Files_importCarTicket_failedWithError Cannot find worksheets",@"Cannot find worksheets within the file.")) ];
}

- (void)importSheet:(GDataEntryDocBase *)sheet {
	if (cancelled) {
		return;
	}
	GDataEntryWorksheet *worksheet = (GDataEntryWorksheet *)sheet;
	NSURL *feedURL = [worksheet listFeedURL];
	if (feedURL) {
		[spreadsheetService fetchSpreadsheetFeedWithURL:feedURL
											   delegate:self
									  didFinishSelector:@selector(importSheetTicket:finishedWithFeed:)
										didFailSelector:@selector(importSheetTicket:failedWithError:)];
	} else {
		[self alertFail:(NSLocalizedString(@"Files_importSheet incomplete data",@"Received incomplete data from Google.")) ];
	}
}

- (void)importSheetTicket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataEntryDocBase *)object {
	if (cancelled) {
		return;
	}
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	[appDelegate addCar:newCar];
	Car *currentCar = [appDelegate currentCar];
	[appDelegate chooseCar:newCar];
//#warning here translate headers in spreadsheet
	NSDateFormatter *formatter = [appDelegate googDateFormatter];
	GDataFeedSpreadsheetList *rows = (GDataFeedSpreadsheetList *) object;
	NSArray *entries = [rows entries];
	for (int i = 0; i < [entries count]; ++i) {
		GDataEntrySpreadsheetList *row = (GDataEntrySpreadsheetList *)[entries objectAtIndex:i];
		NSDate *d = [FuelLogAppDelegate getNoonUTC:[formatter dateFromString:[[row customElementForName:@"date"] stringValue]]];
		float odometer = [[[row customElementForName:@"odometer"] stringValue] floatValue];
		float volume = [[[row customElementForName:@"volume"] stringValue] floatValue];
		float cost = [[[row customElementForName:@"cost"] stringValue] floatValue];
		NSString *full = [[row customElementForName:@"full"] stringValue];
		BOOL isFull = [@"Y" isEqual:full] || [@"Yes" isEqual:full] || [@"y" isEqual:full] || [@"yes" isEqual:full];
		Gas *gas = [[Gas alloc] init:newCar];
		[gas setDate:d];
		[gas setOdometer:odometer];
		[gas setVolume:volume];
		[gas setCost:cost];
		[gas setFull:isFull];
		[appDelegate addGasIfNeeded:gas previous:nil next:nil];
	}
	if (currentCar != nil) {
		[appDelegate chooseCar:currentCar];
	}
	[self alertSuccess];
}

- (void)importSheetTicket:(GDataServiceTicket *)ticket failedWithError:(NSError *)error {
	[self alertFail:(NSLocalizedString(@"Files_importSheetTicket Cannot read data from file.",@"Cannot read data from file.")) ];
}

#pragma mark - UITableView delegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [files count]; 
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	debug(@"in row %d", indexPath.row);
	[self importCar:(GDataEntryDocBase *)[files objectAtIndex:indexPath.row]];

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	static NSString *CellIdentifier = @"Cell";
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
	}
	cell.accessoryType=UITableViewCellAccessoryNone;
 	GDataEntryDocBase * gfile =  (GDataEntryDocBase *)[files objectAtIndex:indexPath.row];
	cell.textLabel.text = [[gfile title] stringValue];
	cell.detailTextLabel.text = (NSLocalizedString(@"FileCell_initWithFrame import",@"import")); 
//	if (row == numericToWorkOn) cell.accessoryType= UITableViewCellAccessoryCheckmark; 
	return cell;
}


#pragma mark UIAlertView

- (void)alertBegin {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	NSString *msg =	[NSString stringWithFormat:(NSLocalizedString(@"Files_alertBegin Importing xxx ...",@"Importing %@ from your Fuel Log folder...")), filename];
	if (alertView) {
		alertView.message = msg;	
	} else {
		alertView = [[UIAlertView alloc] initWithTitle:@"" 
											   message:msg
											  delegate:self 
									 cancelButtonTitle:(NSLocalizedString(@"Files_alertBegin Cancel",@"Cancel")) 
									 otherButtonTitles:nil];
	}
	[alertView show];
}

- (void)alertSuccess {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	// open a alert with an OK
	if (alertView) {
		[alertView dismissWithClickedButtonIndex:-1 animated:YES];
	}
	NSString *msg = [NSString stringWithFormat:(NSLocalizedString(@"Files_alertSuccess Imported xxx as xxx",@"Imported %@ as %@")), filename, newCar.label];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
													message:msg
												   delegate:self 
										  cancelButtonTitle:(NSLocalizedString(@"Files_alertSuccess OK",@"OK" ))
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}

- (void)alertFail:(NSString *)error {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	// open a alert with an OK
	if (alertView) {
		[alertView dismissWithClickedButtonIndex:-1 animated:YES];
	}
	NSString *msg = [NSString stringWithFormat:(NSLocalizedString(@"Files_alertFail Importing xx failed: reason ",@"Importing %@ failed: %@ ")), (filename ? filename : @""), error];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
													message:msg
												   delegate:self 
										  cancelButtonTitle:(NSLocalizedString(@"Files_alertFail OK",@"OK" )) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (alert == alertView && buttonIndex == [alert cancelButtonIndex]) {
		cancelled = YES;
		if (ticket) {
			[ticket cancelTicket];
		}
	}
}

@end
